package com.dream.oproject.base.web.proxy;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dream.oproject.base.dao.IBaseDao;
import com.dream.oproject.base.service.IBaseService;
import com.dream.oproject.demo.service.IDemoInfoService;
import com.dream.oproject.page.PageInfo;
import com.dream.oproject.web.util.ApplicationUtil;

@Controller
@RequestMapping("/proxy/*")
public class ServiceProxyController{
  
	private static final long serialVersionUID = -9038793848009250871L;
	private Integer pageSize = 10;
	private WebApplicationContext wac = null;
	
	@RequestMapping("getPageInfo")
    public @ResponseBody Map<String,Object> getPageInfo(HttpServletRequest httpRequest,Integer page,Integer rows,String methodName,String filter,String sortName,String sortOrder) { 
		if(wac == null){
			wac = WebApplicationContextUtils.getRequiredWebApplicationContext(httpRequest.getSession().getServletContext());  
		}
		IBaseService baseService = (IBaseService)this.getSpringBean(methodName);
		PageInfo pageInfo = new PageInfo();
		if(page == null){
			page = 1;
		}
		pageInfo.setPageNo(page);
		if(rows == null){
			rows = this.pageSize;
		}
		pageInfo.setPageSize(rows);
		pageInfo.setSortName(sortName);
		pageInfo.setSortOrder(sortOrder);
		if(StringUtils.isNotEmpty(filter)){
			Map<String,Object> map = ApplicationUtil.convertJsonToBean(filter, Map.class);
			pageInfo.setFilter(map);
		}
		
		pageInfo = baseService.getObjectListByPage(pageInfo);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", pageInfo.getTotalData());
		result.put("rows", pageInfo.getDatas());
		return result; 
	}
    
	private Object getSpringBean(String beanName) {
		if (beanName != null && beanName.trim().length() > 0) {
			return wac.getBean(beanName);
		} else {
			return null;
		}
	}
}
